#!/usr/bin/python
# coding=utf8
#
# Copyright (C) 2011 XNData contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = "zhangchitc@gmail.com"


import urllib2, urllib
import re
from BeautifulSoup import BeautifulSoup          # For processing HTML
from BeautifulSoup import BeautifulStoneSoup     # For processing XML
import xndata.client
import xndata.data.photo


class PhotoUrlMgr:

    @staticmethod
    def album_list_url (owner_id, cur_page):
        return "http://photo.renren.com/photo/%s/album/relatives?curpage=%d" % (
                owner_id, cur_page)

    @staticmethod
    def photo_list_url (owner_id, album_id, cur_page):
        return "http://photo.renren.com/photo/%s/album-%s?curpage=%d" % (
                owner_id, album_id, cur_page)


    @staticmethod
    def photo_url (owner_id, photo_id):
        return "http://photo.renren.com/photo/%s/photo-%s" % (
                owner_id, photo_id)


class PhotoPageFetcher:

    @staticmethod
    def fetch_album_list_page (opener, owner_id, cur_page):
        request = urllib2.Request (PhotoUrlMgr.album_list_url (owner_id, cur_page))
        return opener.open (request).read ()


    @staticmethod
    def fetch_photo_list_page (opener, owner_id, album_id, cur_page):
        request = urllib2.Request (PhotoUrlMgr.photo_list_url (owner_id, album_id, cur_page))
        return opener.open (request).read ()

    @staticmethod
    def fetch_photo_page (opener, owner_id, photo_id):
        request = urllib2.Request (PhotoUrlMgr.photo_url (owner_id, photo_id))
        return opener.open (request).read ()

     
def nvgstr2str (s):
    return unicode (s).encode ('utf-8')


class PhotoPageParser:
    
    @staticmethod
    def get_total_album (html):
        soup = BeautifulSoup(html)
        node = soup.find("div", { "class" : "float-left number-photo" })
        ret = node.string   # "共xxx个相册"
        ret = ret[1:]       # "xxx个相册"
        ret = ret[:-3]      # "xxx"
        return int (ret)


    @staticmethod
    def get_album_list (html, owner_id, cur_page):
        soup = BeautifulSoup (html)
        node = soup.find ("div", {"class" : "big-album album-list clearfix"})
        alist = node.findAll ("li")

        album_list = xndata.data.photo.AlbumList (owner_id = owner_id, 
                                    cur_page = cur_page)
        
        for album_node in alist:
            # Remember!! BeautifulSoup uses unicode to store strings 
            # So that we need str () all info we got

            # extract album_id
            href = album_node.a["href"]         
            m = re.compile (r"album-(?P<albumid>\d*)").search (href)
            album_id = str (m.group ("albumid"))

            # extract snapshot_url
            style = album_node.a.img["style"]
            m = re.compile (r'url\((")?(?P<url>.*?)(")?\)').search (style)
            snapshot_url = str (m.group ("url"))

            # extract description
            description = nvgstr2str (album_node.span.a.string)
            
            # extract total_photo
            totalstr = album_node.span.span.contents[0].split ('\n')[0]
            total_photo = int (totalstr[:-3])
             
            album_profile = xndata.data.photo.AlbumProfile (
                            owner_id = owner_id, album_id = album_id, snapshot_url = snapshot_url,
                            description = description, total_photo = total_photo)
            album_list.addAlbumProfile (album_profile)

        return album_list


    @staticmethod
    def get_total_photo (html):
        soup = BeautifulSoup (html)

        node = soup.find ("div", { "class" : "float-left number-photo"} )
        s = node.contents[3]
        s = s.split ('/')[1]
        s = s[2:]
        s = s[:-1]
        return int (s)


    @staticmethod
    def get_photo_list (html, owner_id, album_id, cur_page):
        soup = BeautifulSoup (html)
        
        node = soup.find ("div", { "class" : "Information" })
        name = nvgstr2str (node.h1.string)
        site_node = node.find ("p", { "class" : "site" })
        if site_node is not None:
            site = nvgstr2str (site_node.string)
            site = site.split (':')[1]
            site = site[1:]
        else:
            site = ""

        m = re.compile (r"var albumDes =  '(?P<desc>.*)';").search (html)
        description = str (m.group ("desc"))

        photo_list = xndata.data.photo.PhotoList (owner_id = owner_id, 
            album_id = album_id, cur_page = cur_page, name = name, 
            site = site, description = description)
        plist = soup.find ("div",  { "class" : "photo-list big-photo-list clearfix" }).findAll ("li")
        
        for photo_node in plist:
            # extract photo_id
            href = photo_node.a["href"]
            m = re.compile (r"photo-(?P<photoid>\d*)").search (href)
            photo_id = str (m.group ("photoid" ))

            # extract snapshot_url
            style = photo_node.a.img["style"]
            m = re.compile (r'url\((")?(?P<url>.*?)(")?\)').search (style)
            snapshot_url = str (m.group ("url"))

            # extract description
            if photo_node.span.string is not None:
                description = nvgstr2str (photo_node.span.string)
            else:
                description = ""
            
            photo_profile = xndata.data.photo.PhotoProfile (
                            owner_id = owner_id, photo_id = photo_id, 
                            snapshot_url = snapshot_url, description = description)
            photo_list.addPhotoProfile (photo_profile)

        return photo_list

    @staticmethod
    def get_photo_detail (html, owner_id, photo_id):
        soup = BeautifulSoup (html)
        
        node = soup.find ("textarea", { "id" : "description" } )
        description = nvgstr2str (node.string)

        m = re.compile (r'"largeurl":"(?P<url>.*?)"').search (html)
        url = m.group ("url")
        url = url.replace ("\\", "")
        return xndata.data.photo.PhotoDetail (owner_id = owner_id,
                photo_id = photo_id, large_url = url, description = description)


if __name__ == "__main__":
    client = xndata.client.XNClient ("zhangchitc@gmail.com", "aaaaaaaa")
    #html = PhotoPageFetcher.fetch_album_list_page (client.opener, "242124580", 0)
    #print PhotoPageParser.get_album_list (html)
    # other's album
    #html = PhotoPageFetcher.fetch_photo_list_page (client.opener, "247780420", "282652960", 1)
    # my album
    #html = PhotoPageFetcher.fetch_photo_list_page (client.opener, "242124580", "432244996", 0)
    #print PhotoPageParser.get_photo_list (html)
    html = PhotoPageFetcher.fetch_photo_page (client.opener, "247780420", "4136453711")
    print PhotoPageParser.get_photo_detail (html, "247780420", "4136453711")


